//
//  RegisterSViewController.m
//  SelfDriving
//
//  Created by apple on 16/1/8.
//  Copyright © 2016年 apple. All rights reserved.
//

#import "RegisterSViewController.h"
#import "UIDatePickerView.h"
#import "OccupationVC.h"
#import "CityViewController.h"
#import "AutographViewController.h"
#import <AVFoundation/AVCaptureDevice.h>
#import <AVFoundation/AVMediaFormat.h>
@interface RegisterSViewController ()<UIDatePickerViewDelegate,OccupationVCDelegate,CityViewControllerDelegate,AutographViewControllerDelegate,UITextViewDelegate>
@property (weak, nonatomic) IBOutlet UITextField *nicknameField;
@property (weak, nonatomic) IBOutlet UILabel *time;
@property (weak, nonatomic) IBOutlet UILabel *jobLabel;
@property (weak, nonatomic) IBOutlet UIButton *btn_n;
@property (weak, nonatomic) IBOutlet UILabel *hometownLabel;
@property (weak, nonatomic) IBOutlet UILabel *qianming;
@property (weak, nonatomic) IBOutlet UITextView *qianmingText;
@property (weak, nonatomic) IBOutlet UIButton *btn_v;
@property (weak, nonatomic) IBOutlet UIButton *imgBtn;
@end
@implementation RegisterSViewController{
    int gender;
    UIDatePickerView *datePickerView;
    NSString *end_time;
    NSString *hometown;//城市ID
    NSData *imageData;
}
-(void)viewWillAppear:(BOOL)animated{
    self.navigationController.navigationBarHidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _qianmingText.textAlignment = NSTextAlignmentRight;
    
    for (int i=90; i<91; i++) {
        UIButton *btn =(UIButton *)[self.view viewWithTag:i];
        btn.selected = YES;
    }
    
    //第三方登录
    if (_model) {
        _nicknameField.text = _model.nickname;
        imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:_model.headsmall]];
        UIImage  *img = [UIImage imageWithData:imageData];
        //之前没有判断img是否为nil(xhw11月6号改)
        if (img == nil) {
            [_imgBtn setImage:[UIImage imageNamed:@"addphoto.png"] forState:UIControlStateNormal];
        }
        else {
            [_imgBtn setImage:img forState:UIControlStateNormal];
        }
        
        _uid = _model.uid;
    }
    if (_iseit) {
        [[AppDelegate shareDelegate]refuser:_model.uid success:^(id as) {
            _model = as;
            _nicknameField.text = _model.nickname;
            imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:_model.headsmall]];
            UIImage  *img = [UIImage imageWithData:imageData];
            if (img == nil) {
                [_imgBtn setImage:[UIImage imageNamed:@"addphoto.png"] forState:UIControlStateNormal];
            }
            else {
                [_imgBtn setImage:img forState:UIControlStateNormal];
            }
//            [_imgBtn setImage:img forState:UIControlStateNormal];
            if([_model.gender intValue] == 0){
                _btn_n.selected = YES;
                _btn_v.selected = NO;
            }else{
                _btn_v.selected = YES;
                _btn_n.selected = NO;
            }
            _time.text = [ValidateHelper doubleConvertDate:[_model.age doubleValue] FormatterStr:@"yyyy年MM月dd日"];
            _hometownLabel.text = _model.hometown;
            _jobLabel.text = _model.job;
            _qianmingText.text = _model.sign;
            end_time = [ValidateHelper doubleConvertDate:[_model.age doubleValue] FormatterStr:@"yyyy-MM-dd"];

        }];
    }
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}
- (IBAction)genderAction:(UIButton *)sender {
    for (int i=90; i<92; i++) {
        UIButton *btn =(UIButton *)[self.view viewWithTag:i];
        btn.selected = NO;
    }
    sender.selected = YES;
    if ([[sender.titleLabel.text trim] isEqualToString:@"男"]) {
        gender = 0;
    }else{
        gender = 1;
    }
}
#pragma  mark 年龄
- (IBAction)ageAction:(UIButton *)sender {
    [self.view endEditing:YES];
    datePickerView = [[UIDatePickerView alloc] initWithFrame:CGRectMake(15, SCRE_HEIGHT, SCRE_WIDTH-30, 180)];
    datePickerView.backgroundColor = [UIColor whiteColor];
    datePickerView.delegate = self;
    datePickerView.lanel_title.text = @"开始时间";
    [datePickerView up];
    [[[[UIApplication sharedApplication] windows] firstObject] addSubview:datePickerView];
}
- (void)didSelectDate:(UIDatePickerView *)pickerView Date:(NSMutableDictionary *)date
{
    NSString *dates = [date objectForKey:@"dates"];
    if ([self isBeyondDateNow:dates]) {
        [SVProgressHUD showErrorWithStatus:@"请选择正确的年龄"];
    }
    else {
        _time.text = [date objectForKey:@"date"];
        end_time = [date objectForKey:@"dates"];
    }
//    _time.text = [date objectForKey:@"date"];
//    end_time = [date objectForKey:@"dates"];
    pickerView.hidden = YES;
}
//xhw2018-2-28加
- (BOOL)isBeyondDateNow: (NSString *)startTime {
    NSDate *now = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *startDate = [formatter dateFromString:startTime];
    NSString *nowstr = [formatter stringFromDate:now];
    NSDate *nowDate = [formatter dateFromString:nowstr];
    
    NSTimeInterval start = [startDate timeIntervalSince1970];
    NSTimeInterval end = [nowDate timeIntervalSince1970];
    NSTimeInterval value = start - end;
    
    if (value >= 0) {
        return YES;
    }
    else {
        return NO;
    }
}
#pragma mark 故乡
- (IBAction)hometownAction:(id)sender {
    [self.view endEditing:YES];
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"U"
                                                                 bundle:[NSBundle mainBundle]];
    CityViewController *viewcv = [customerStoryboard instantiateViewControllerWithIdentifier:@"CityViewController"];
    viewcv.view.backgroundColor = [UIColor clearColor];
    viewcv.delegate = self;
    viewcv.modalPresentationStyle= UIModalPresentationOverFullScreen;
    [self presentViewController:viewcv animated:YES completion:nil];
    
}
#pragma mark 故乡回调
-(void)didSelectDate:(NSString *)name id:(NSString *)id{
    _hometownLabel.text = name;
    hometown = id;
}
#pragma  mark 职业
- (IBAction)jobAction:(UIButton *)sender {
    [self.view endEditing:YES];
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"U"
                                                                 bundle:[NSBundle mainBundle]];
    OccupationVC *viewcv = [customerStoryboard instantiateViewControllerWithIdentifier:@"OccupationVC"];
    viewcv.delegate = self;
    [self.navigationController pushViewController:viewcv animated:YES];
}
#pragma  mark 职业回调
-(void)didSelectDate:(NSString *)name{
    _jobLabel.text = name;
}
#pragma mark 签名
- (IBAction)autographAction:(UIButton *)sender {
    [self.view endEditing:YES];
    UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"U"
                                                                 bundle:[NSBundle mainBundle]];
    AutographViewController *viewcv = [customerStoryboard instantiateViewControllerWithIdentifier:@"AutographViewController"];
    viewcv.delegate = self;
    [self.navigationController pushViewController:viewcv animated:YES];
}
#pragma mark 签名回调
-(void)didSelectDates:(NSString *)name{
    _qianming.text = name;
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    NSUInteger proposedNewLength = textView.text.length - range.length + text.length;
    if ([textView.text isEqualToString:@"请输入签名"]) {
        textView.text = @"";
    }
    if (proposedNewLength > 300)
        return NO;//限制长度
    return YES;
}

#pragma mark 相机
- (IBAction)potoAction:(id)sender {
    [self.view endEditing:YES];
    UIActionSheet *sctionsheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"照相" otherButtonTitles:@"选择相册", nil];
    [sctionsheet showInView:self.view];
}
-(void)actionSheet:(UIActionSheet *)actionSheet willDismissWithButtonIndex:(NSInteger)buttonIndex{
    
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    
    if (authStatus == AVAuthorizationStatusRestricted ||
        
        authStatus ==AVAuthorizationStatusDenied){
        
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"警告" message:@"加载相机失败，请确认隐私设置中相机权限已打开！" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
        
    }
    if (buttonIndex == 0) {
        UIImagePickerController *imagePickerVC = [[UIImagePickerController alloc] init];
        imagePickerVC.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePickerVC.delegate = self;
        imagePickerVC.allowsEditing = YES;
        [self presentViewController:imagePickerVC
                           animated:NO
                         completion:nil];
        
    }
    if (buttonIndex == 1) {
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:imagePickerController animated:NO completion:^{}];
    }
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    imageData = UIImageJPEGRepresentation([info objectForKey:UIImagePickerControllerEditedImage],0.00001);
    UIImage  *img = [UIImage imageWithData:imageData];
    [_imgBtn setImage:img forState:UIControlStateNormal];
    [picker dismissViewControllerAnimated:NO completion:nil];
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:NO completion:nil];
}
- (IBAction)SubmitAction:(UIButton *)sender {
    if ([_nicknameField.text trim].length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入姓名"];
        return;
    }
    if (!end_time) {
        [SVProgressHUD showErrorWithStatus:@"请选择年龄"];
        return;
    }
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setObject:[_nicknameField.text trim] forKey:@"nickname"];
    [dic setObject:[NSNumber numberWithInt:gender] forKey:@"gender"];
    [dic setObject:_jobLabel.text forKey:@"job"];
    [dic setObject:hometown?hometown:@"" forKey:@"hometown"];
    [dic setObject:_qianmingText.text forKey:@"sign"];
    [dic setObject:[NSNumber numberWithInteger:[ValidateHelper cTimestampFromString:[NSString stringWithFormat:@"%@ 0:0:0",end_time] format:@"yyyy-MM-dd HH:mm:ss"]] forKey:@"age"];
    [dic setObject:_uid forKey:@"uid"];
    NSMutableArray *imgdata =[[NSMutableArray alloc]init];
    if (imageData) {
        NSMutableDictionary *dici = [[NSMutableDictionary alloc]init];
        [dici setObject:@"images" forKey:@"key"];
        [dici setObject:imageData forKey:@"value"];
        [imgdata addObject:dici];
    }
    NSMutableURLRequest *request = [[BusinessService shareInstance]postRequestWithURL:completeInfo postParems:dic data:imgdata];
    [[NSURLConnection connectionWithRequest:request delegate:self] start];
}
- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite {
    float progress = [[NSNumber numberWithInteger:totalBytesWritten] floatValue];
    float total = [[NSNumber numberWithInteger: totalBytesExpectedToWrite] floatValue];
    float progres = progress/total;
    [SVProgressHUD showProgress:progres status:@"创建中..."];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)datas{
    NSString *request= [[NSString alloc] initWithData:datas encoding:NSUTF8StringEncoding];
    NSMutableDictionary *result = [NSMutableDictionary dictionary];
    result = [ValidateHelper jsonStringToDictionary:request];
    LoginResponseModel *model = [[LoginResponseModel alloc] init];
    [model serializationWithDictionary:[result objectForKey:@"data"]];
    
    int code = [[[result objectForKey:@"state"] objectForKey:@"code"] intValue];
    if(code == 0){
        [SVProgressHUD dismiss];
        if ([model.type intValue]!=0) {
            [AppDelegate shareDelegate].user = model;
            NSString *uid = [NSString stringWithFormat:@"%@",[AppDelegate shareDelegate].user.uid];
            [[AppDelegate shareDelegate] userDidLogin:uid pwd:model.openfire];
            [[AppDelegate shareDelegate] initbar];
        }else if(_iseit){
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [UserDefaults writeUserDefaultObjectValue:self.dic withKey:@"ruser"];
            UIStoryboard *customerStoryboard = [UIStoryboard storyboardWithName:@"U"
                                                                         bundle:[NSBundle mainBundle]];
            UIViewController *searchResultDetailController = [customerStoryboard instantiateViewControllerWithIdentifier:@"LoginVC"];
            [self.navigationController pushViewController:searchResultDetailController animated:YES];
        }
        
    }else{
        [SVProgressHUD showErrorWithStatus:[[result objectForKey:@"state"] objectForKey:@"msg"]];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)backAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


@end
